/**
 * @class datagrid-boots.js
 * @author jiagui E-mail:<zhujiagui@zkingsoft.com>
 * @date 2015年7月15日 下午4:51:11
 * @description 基于bootstrap样式，对表格等数据的处理进行封装调用
 */
(function($) {
	function DataGrid() {
		this.count = 1;
	}
	$
			.extend(
					DataGrid.prototype,
					{
						init : function(opts) {// 表格初始化
							var _datagrid = opts.datagrid;
							var sortField = _datagrid.attr("sortField");// 排序字段
							var sortOrder = _datagrid.attr("sortOrder");// 排序方式
							var dataField = _datagrid.attr("dataField");// 数据字段名
							var pageSize = _datagrid.attr("pageSize");// 每页多少条
							if (pageSize == null || pageSize == undefined
									|| pageSize == 0) {
								pageSize = 10;
							}
							var defaultData = {
								sortField : sortField,// 排序字段
								sortOrder : sortOrder,// 排序方式
								pageSize : pageSize,// 每页显示条数
								currentPage : 1
							// 当前页码
							};
							opts.data = defaultData;
							$.grid.loadData(opts, null);
						},
						loadData : function(opts, searchData) {
							var _datagrid = opts.datagrid;
							if (_datagrid == null || _datagrid == undefined) {
								return;
							}
							var url = _datagrid.attr("url");// 数据加载地址
							if (url == null || url == "") {
								return;
							}
							if (searchData != null) {
								if (url.indexOf("?") >= 0) {
									url += "&" + searchData;// 拼接查询参数
								} else {
									url += "?" + searchData;
								}
							}
							$btools.blockUI({
								msg : "加载数据中，请稍后..."
							});
							$
									.ajax({
										cache : true,
										async : false,
										type : "POST",
										url : url,
										data : opts.data,
										error : function(request) {
											$btools.alert("请求出错~", function() {
												$btools.unblockUI();// 隐藏加载提示框
											});
											return;
										},
										success : function(data) {
											setTimeout(function() {
												$btools.unblockUI();// 隐藏加载提示框
											}, 100);
											if (data == null) {
												$btools.alert("查询数据失败!");
											} else if (data.code == "true") {
												try {
													var type = _datagrid
															.attr("type");// 表格类型，默认为datagrid(普通表格),treegrid（树形表格）
													if (type != null
															|| type != undefined
															&& type == "treegrid") {
														$.grid.showTreeData(
																opts, data);// 显示数据
													} else {
														$.grid.showData(opts,
																data);// 显示数据
													}
													$.grid
															.loadPager(opts,
																	data);//
													$.grid.loadSuccess(opts);
													// 显示分页信息
												} catch (e) {
													$btools.alert(e);
												}
											} else {
												if (data.result["msg"] != null) {
													$btools
															.alert(data.result["msg"]);
												} else {
													$btools.alert("请求出错~");
												}
											}
										}
									});
						},
						showData : function(opts, data) {// 加载数据
							var _datagrid = opts.datagrid;
							var dataField = _datagrid.attr("dataField");
							if (dataField != null
									&& data.result[dataField] != null) {
								var dataList = data.result[dataField];
								var ths = _datagrid.find("table>thead>tr>th");
								var multiSelect = _datagrid.attr("multiSelect");// 允许多选行
								var idField = _datagrid.attr("idField");// 主键字段
								var sortField = _datagrid.attr("sortField");// 排序字段
								var sortOrder = _datagrid.attr("sortOrder");// 排序方式
								var rowCls = _datagrid.attr("rowCls");
								if (rowCls == null || rowCls == undefined) {
									rowCls = "row_cls";
								}
								_datagrid.find("table>tbody").remove();// 防止查询数据为空时还存在数据显示
								if (ths.length > 0 && dataList != null
										&& dataList.length > 0) {
									var html = "<tbody>";
									var contentcls = null;
									var fieldName = null;
									var indextype = null;
									var primarykey = null;
									var content = null;
									var renderer = null;
									var dateFormat = null;
									var _this = null;
									var rendererData = null;
									var headhtml = "<thead>";
									for (var i = 0, length = dataList.length; i < length; i++) {
										html += "<tr class='" + rowCls + "'>";
										ths
												.each(function(index, e) {
													_this = $(e);
													content = "";
													renderer = null;
													rendererData = null;
													dateFormat = null;
													fieldName = _this
															.attr("name");
													contentcls = _this
															.attr("contentcls");
													renderer = _this
															.attr("renderer");
													indextype = _this
															.attr("type");
													dateFormat = _this
															.attr("dateFormat");
													if (contentcls != null
															&& contentcls != undefined) {
														html += "<td class='"
																+ contentcls
																+ "'";
													} else {
														html += "<td";
													}
													if (fieldName != null
															&& fieldName != undefined) {
														html += " name='"
																+ fieldName
																+ "'>";
													} else {
														html += ">";
													}
													for ( var name in dataList[i]) {
														if (name == idField) {
															primarykey = dataList[i][name];
														}
														if (fieldName == name
																.toString()) {
															if (renderer != null
																	&& renderer != undefined) {
																// 根据函数名执行函数
																rendererData = {
																	value : dataList[i][name],
																	record : dataList[i]
																};
																eval("var _function = "
																		+ renderer);
																content = _function(rendererData);
															} else {
																content = dataList[i][name];
															}
														}
													}
													try {
														if (dateFormat != null
																&& dateFormat != undefined
																&& content != null
																&& content != "") {
															if (typeof content == "string") {
																content = new Date(
																		Date
																				.parse(content
																						.toString()
																						.replace(
																								/-/g,
																								"/")))
																		.format(dateFormat);
															} else {
																content
																		.format(dateFormat);
															}
														}
													} catch (e) {
														$btools.alert(e);
													}
													if (i == 0) {
														var allowSort = _this
																.attr("allowSort");
														if (allowSort != null
																&& allowSort != undefined
																&& allowSort == "true") {
															_this.css("cursor",
																	"pointer");
															var icon = document
																	.createElement("i");
															icon.style.float = "right";
															if (fieldName == sortField) {
																if (sortOrder == "desc") {
																	icon
																			.setAttribute(
																					"class",
																					"icon-sort-down");
																} else if (sortOrder == "asc") {
																	icon
																			.setAttribute(
																					"class",
																					"icon-sort-up");
																}
															} else {
																icon
																		.setAttribute(
																				"class",
																				"icon-sort");
															}
															_this.find("i")
																	.remove();// 删除原有的图标元素
															e.appendChild(icon);// 添加排序图标
														}
														if (indextype != null
																&& indextype != undefined) {
															if (indextype == "checkcolumn"
																	&& (multiSelect == null
																			|| multiSelect == undefined || multiSelect == "true")) {
																var thisths = _this
																		.prop(
																				"outerHTML")
																		.split(
																				">");
																headhtml += thisths[0]
																		+ "><label><input type='checkbox' class='checkAll' /></label></th>";
															} else {
																headhtml += _this
																		.prop("outerHTML");
															}
														} else {
															headhtml += _this
																	.prop("outerHTML");
														}
													}
													if (indextype != null
															&& indextype != undefined) {
														if (indextype == "indexcolumn") {
															html += "<label>"
																	+ (i + 1)
																	+ "</label>";
														} else if (indextype == "checkcolumn") {
															if (multiSelect != null
																	&& multiSelect != undefined
																	&& multiSelect == "false") {// 单选，默认多选
																html += "<label><input type='radio' class='singlecheck' name='idField_select'  value='"
																		+ primarykey
																		+ "'/></label>";
															} else {
																html += "<label><input type='checkbox' class='subcheck' name='idField_checkbox' value='"
																		+ primarykey
																		+ "'/></label>";
															}
														}
													} else {
														html += content;
													}
													html += "</td>";
												});
										html += "</tr>";
									}
									html += "</tbody>";
									_datagrid.find("table").html(
											headhtml + "</thead>" + html);
								}
							}
							$.grid.ifCheckedOnRowClick(opts);
							var ondataload = _datagrid.attr("ondataload");
							if (ondataload != null && ondataload != undefined) {// 数据加载完成之后执行
								if (ondataload.indexOf("()") > 0) {
									eval(ondataload);
								} else {
									eval(ondataload + "(" + ")");
								}
							}
						},
						drawRows : function(opts, dataList, parentTarget, num) {
							var contentcls = null;
							var fieldName = null;
							var indextype = null;
							var primarykey = null;
							var content = null;
							var renderer = null;
							var dateFormat = null;
							var _this = null;
							var rendererData = null;
							var target = "target" + $.grid.count;
							var headcontent = "";
							for (var i = 0, length = dataList.length; i < length; i++) {
								headcontent = "";
								$.grid.count++;
								target = "target" + $.grid.count;
								opts.tr = document.createElement("tr");
								opts.tr.setAttribute("class", opts.rowCls);
								opts.tr.setAttribute("selfTarget", target);
								if (parentTarget != null) {
									opts.tr.setAttribute("parentTarget",
											parentTarget);
								}
								opts.ths
										.each(function(index, e) {
											_this = $(e);
											content = "";
											renderer = null;
											rendererData = null;
											dateFormat = null;
											fieldName = _this.attr("name");
											contentcls = _this
													.attr("contentcls");
											renderer = _this.attr("renderer");
											indextype = _this.attr("type");
											dateFormat = _this
													.attr("dateFormat");
											opts.td = document
													.createElement("td");
											if (fieldName != null
													&& fieldName != undefined) {
												opts.td.setAttribute("name",
														fieldName);
											}
											if (contentcls != null
													&& contentcls != undefined) {
												opts.td.setAttribute("class",
														contentcls);
											}
											for ( var name in dataList[i]) {
												if (name == opts.idField) {
													primarykey = dataList[i][name];
												}
												if (fieldName == name
														.toString()) {
													if (renderer != null
															&& renderer != undefined) {
														// 根据函数名执行函数
														rendererData = {
															value : dataList[i][name],
															record : dataList[i]
														};
														eval("var _function = "
																+ renderer);
														content = _function(rendererData);
													} else {
														content = dataList[i][name];
													}
													if (opts.treeColumn != null
															&& opts.treeColumn != undefined
															&& opts.treeColumn == name) {
														if (dataList[i].firstNode != null
																&& dataList[i].firstNode != undefined
																&& !dataList[i].firstNode) {
															if (opts.expandOnLoad == null
																	|| opts.expandOnLoad == undefined) {
																opts.tr.style.display = "none";
															}
															for (var j = 0; j < num; j++) {
																headcontent += "&nbsp;&nbsp;&nbsp;";
															}
														}
														opts.iconspan = document
																.createElement("span");
														if (dataList[i].children != null
																&& dataList[i].children.length > 0) {
															if (opts.expandOnLoad != null
																	&& opts.expandOnLoad != undefined) {
																opts.iconspan
																		.setAttribute(
																				"class",
																				opts.parentIconOpen);
															} else {
																opts.iconspan
																		.setAttribute(
																				"class",
																				opts.parentIconClose);
															}
															var abtn = document
																	.createElement("a");
															abtn
																	.setAttribute(
																			"href",
																			"javascript:void(0)");
															abtn.style.textDecoration = "none";
															abtn
																	.appendChild(opts.iconspan);
															$(opts.td)
																	.append(
																			headcontent);
															opts.td
																	.appendChild(abtn);
														} else {
															opts.iconspan
																	.setAttribute(
																			"class",
																			opts.childIcon);
															$(opts.td)
																	.append(
																			headcontent);
															opts.td
																	.appendChild(opts.iconspan);
														}
													}
												}
											}
											if (indextype != null
													&& indextype != undefined) {
												if (indextype == "indexcolumn") {
													content += "<label>"
															+ ($(opts.tbody)
																	.find("tr").length + 1)
															+ "</label>";
												} else if (indextype == "checkcolumn") {
													if (opts.multiSelect != null
															&& opts.multiSelect != undefined
															&& opts.multiSelect == "false") {// 单选，默认多选
														content = "<label><input type='radio' class='singlecheck' name='idField_select'  value='"
																+ primarykey
																+ "'/></label>";
													} else {
														content = "<label><input type='checkbox' class='subcheck' name='idField_checkbox' value='"
																+ primarykey
																+ "'/></label>";
													}
												}
											} else {
												try {
													if (dateFormat != null
															&& dateFormat != undefined
															&& content != null
															&& content != "") {
														if (typeof content == "string") {
															content = new Date(
																	Date
																			.parse(content
																					.toString()
																					.replace(
																							/-/g,
																							"/")))
																	.format(dateFormat);
														} else {
															content
																	.format(dateFormat);
														}
													}
												} catch (e) {
													$btools.alert(e);
												}
											}
											$(opts.td).append(
													"&nbsp;" + content);
											opts.tr.appendChild(opts.td);
										});
								opts.tr.appendChild(opts.td);
								opts.tbody.appendChild(opts.tr);
								if (dataList[i].children != null
										&& dataList[i].children.length > 0) {
									if (opts.expandOnLoad == null
											|| opts.expandOnLoad == undefined) {
										opts.tr.setAttribute("status", "close");// 展开
									} else {
										opts.tr.setAttribute("status", "open");// 闭合
									}
									$.grid.drawRows(opts, dataList[i].children,
											target, num + 2);// 递归
								}
							}
							return opts.tbody;
						},
						showTreeData : function(options, data) {// 加载树形表格数据
							var defaults = {
								parentIconClose : "icon-folder-close",// 父节点收拢图标
								parentIconOpen : "icon-folder-open",// 子节点展开图标
								childIcon : "icon-credit-card"// 子节点图标
							};
							var _datagrid = options.datagrid;
							var multiSelect = _datagrid.attr("multiSelect");// 允许多选行
							var idField = _datagrid.attr("idField");// 主键字段
							var sortField = _datagrid.attr("sortField");// 排序字段
							var sortOrder = _datagrid.attr("sortOrder");// 排序方式
							var dataField = _datagrid.attr("dataField");
							var treeColumn = _datagrid.attr("treeColumn");
							var expandOnLoad = _datagrid.attr("expandOnLoad");
							var rowCls = _datagrid.attr("rowCls");
							if (rowCls == null || rowCls == undefined) {
								rowCls = "row_cls";
							}
							var ths = _datagrid.find("table>thead>tr>th");
							var headhtml = "<thead>";
							if (dataField != null
									&& data.result[dataField] != null) {
								var dataList = data.result[dataField];
								var parentIconClose = _datagrid
										.attr("parentIconClose");
								var parentIconOpen = _datagrid
										.attr("parentIconOpen");
								var childIcon = _datagrid.attr("childIcon");
								var affectParentField = _datagrid
										.attr("affectParentField");// 父子关系字段（父级对应的字段）
								var affectChildField = _datagrid
										.attr("affectChildField");// 父子关系字段（子级对应的字段）
								if (affectParentField == null
										|| affectParentField == undefined
										|| affectChildField == null
										|| affectChildField == undefined) {
									throw new Error(
											"表格必填属性(affectParentField或affectChildField)错误!");
								}
								if (parentIconClose != null
										&& parentIconClose != undefined
										&& parentIconClose != "") {
									options.parentIconClose = parentIconClose;
								}
								if (parentIconOpen != null
										&& parentIconOpen != undefined
										&& parentIconOpen != "") {
									options.parentIconOpen = parentIconOpen;
								}
								if (childIcon != null && childIcon != undefined
										&& childIcon != "") {
									options.childIcon = childIcon;
								}
								var opts = $.extend(defaults, options);
								_datagrid.find("table>tbody").remove();// 防止查询数据为空时还存在数据显示
								if (ths.length > 0 && dataList != null
										&& dataList.length > 0) {
									dataList = $.grid
											.toTreeData(dataList,
													affectParentField,
													affectChildField);
									var fieldName = null;
									var indextype = null;
									ths
											.each(function(index, e) {
												_this = $(e);
												fieldName = _this.attr("name");
												indextype = _this.attr("type");
												var allowSort = _this
														.attr("allowSort");
												if (allowSort != null
														&& allowSort != undefined
														&& allowSort == "true") {
													_this.css("cursor",
															"pointer");
													var icon = document
															.createElement("i");
													icon.style.float = "right";
													if (fieldName == sortField) {
														if (sortOrder == "desc") {
															icon
																	.setAttribute(
																			"class",
																			"icon-sort-down");
														} else if (sortOrder == "asc") {
															icon
																	.setAttribute(
																			"class",
																			"icon-sort-up");
														}
													} else {
														icon.setAttribute(
																"class",
																"icon-sort");
													}
													_this.find("i").remove();// 删除原有的图标元素
													e.appendChild(icon);// 添加排序图标
												}
												if (indextype != null
														&& indextype != undefined) {
													if (indextype == "checkcolumn"
															&& (multiSelect == null
																	|| multiSelect == undefined || multiSelect == "true")) {
														var thisths = _this
																.prop(
																		"outerHTML")
																.split(">");
														headhtml += thisths[0]
																+ "><label><input type='checkbox' class='checkAll' /></label></th>";
													} else {
														headhtml += _this
																.prop("outerHTML");
													}
												} else {
													headhtml += _this
															.prop("outerHTML");
												}
											});
									var tbody = document.createElement("tbody");
									var tr = null;
									var td = null;
									opts.tbody = tbody;
									opts.tr = null;
									opts.td = null;
									opts.ths = ths;
									opts.rowCls = rowCls;
									opts.treeColumn = treeColumn;
									opts.idField = idField;
									opts.iconspan = null;
									opts.multiSelect = multiSelect;
									opts.expandOnLoad = expandOnLoad;
									tbody = $.grid.drawRows(opts, dataList,
											null, 0);
									_datagrid.find("table").html(
											headhtml + "</thead>"
													+ $(tbody).html());
								}
							}
							$.grid.ifCheckedOnRowClick(opts);
						},
						toTreeData : function(data, affectParentField,
								affectChildField) {
							var pos = {};
							var tree = [];
							var i = 0;
							while (data.length != 0) {
								if (data[i][affectChildField] == null
										|| data[i][affectChildField] == "") {
									data[i].children = [];
									data[i].firstNode = true;// 第一节点
									tree.push(data[i]);
									pos[data[i][affectParentField]] = [ tree.length - 1 ];
									data.splice(i, 1);
									i--;
								} else {
									var posArr = pos[data[i][affectChildField]];
									if (posArr != undefined) {
										var obj = tree[posArr[0]];
										for (var j = 1; j < posArr.length; j++) {
											obj = obj.children[posArr[j]];
										}
										data[i].children = [];
										data[i].firstNode = false;
										obj.children.push(data[i]);
										pos[data[i][affectParentField]] = posArr
												.concat([ obj.children.length - 1 ]);
										data.splice(i, 1);
										i--;
									}
								}
								i++;
								if (i > data.length - 1) {
									i = 0;
								}
							}
							return tree;
						},
						loadPager : function(opts, data) {// 创建分页视图
							var _datagrid = opts.datagrid;
							var pageVoField = _datagrid.attr("pageVoField");
							var showPager = _datagrid.attr("showPager");// 是否显示分页
							var pageSize = _datagrid.attr("pageSize");
							var pages = _datagrid
									.find("div[class='page_grid_foot']");
							if (showPager == null || showPager == undefined
									|| showPager == "true") {
								if (pages == null || pages === undefined
										|| pages.length == 0) {
									_datagrid
											.append("<div class='page_grid_foot'></div>");// 往table标签后面追加分页标签
								}
								var showReloadButton = _datagrid
										.attr("showReloadButton");// 显示"刷新"按钮
								var sizeList = _datagrid.attr("sizeList");
								var sizeLists = [ 10, 50, 100 ];
								if (sizeList != null && sizeList != undefined) {
									sizeLists = eval('(' + sizeList + ')');// 将字符串转为数组对象
								}
								var pageVo = {
									sortField : "",// 排序字段
									sortOrder : "",// 排序方式
									pageSize : 10,// 每页显示条数
									currentPage : 1,
									totalPage : 0,
									totalRecord : 0
								};
								if (data != null && pageVoField != null
										&& pageVoField != undefined
										&& data.result[pageVoField] != null) {
									pageVo = data.result[pageVoField];
								}
								if (pageSize != null && pageSize != undefined
										&& pageSize > 0) {
									if (sizeLists.indexOf(parseInt(pageSize)) < 0) {
										sizeLists.push(parseInt(pageSize));// 将默认的每页显示的条数加入到页面尺寸集合中
									}
								}
								sizeLists.sort(function(a, b) {
									return a > b ? 1 : -1
								});// 数组按从小到大排序
								_datagrid.attr("sizeList", "["
										+ sizeLists.toString() + "]");
								pages = _datagrid
										.find("div[class='page_grid_foot']");
								if (pages.length > 0) {// 如果已经存在该分页标签，则往标签中加分页信息
									var html = "<label class='pager-left'>每页显示<select size='1' class='select_pagesize'>";
									for (var i = 0, a = sizeLists.length; i < a; i++) {
										if (pageVo.pageSize == sizeLists[i]) {
											html += "<option value='"
													+ sizeLists[i]
													+ "'selected='selected'>"
													+ sizeLists[i]
													+ "</option>";
										} else {
											html += "<option value='"
													+ sizeLists[i] + "'>"
													+ sizeLists[i]
													+ "</option>";
										}
									}
									html += "</select>";
									html += "条</label> <label class='pager-center'>";
									if (pageVo.currentPage == 1
											|| pageVo.totalPage == 0) {
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='first' title='首页' disabled='disabled'>";
										html += "<span class='icon-fast-backward' aria-hidden='true'></span></button>";
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='prev' title='上一页' disabled='disabled'>";
										html += "<span class='icon-backward' aria-hidden='true'></span></button>";
									} else {
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='first' title='首页' data-toggle='tooltip' data-placement='top'>";
										html += "<span class='icon-fast-backward' aria-hidden='true'></span></button>";
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='prev' title='上一页' data-toggle='tooltip' data-placement='top'>";
										html += "<span class='icon-backward' aria-hidden='true'></span></button>";
									}
									html += "<span class='currentPage'>"
											+ pageVo.currentPage
											+ "</span>/<span class='totalPage'>"
											+ pageVo.totalPage + "</span>";
									if (pageVo.currentPage == pageVo.totalPage
											|| pageVo.totalPage == 0) {
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='next' title='下一页' disabled='disabled'>";
										html += "<span class='icon-forward' aria-hidden='true'></span></button>";
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='last' title='尾页' disabled='disabled'>";
										html += "<span class='icon-fast-forward' aria-hidden='true'></span></button>";
									} else {
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='next' title='下一页' data-toggle='tooltip' data-placement='top'>";
										html += "<span class='icon-forward' aria-hidden='true'></span></button>";
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='last' title='尾页' data-toggle='tooltip' data-placement='top'>";
										html += "<span class='icon-fast-forward' aria-hidden='true'></span></button>";
									}
									html += "</label><label class='pager-common'><span style='margin-left: 20px;'>跳转到第</span><input type='text'/>页"
									html += "<button type='button' class='btn btn-default pager-btn go' page-btn-fn='go' title='跳转到' data-toggle='tooltip' data-placement='top'>";
									html += "<span class='icon-arrow-right' aria-hidden='true'></span>GO</button>";
									if (showReloadButton == null
											|| showReloadButton == undefined
											|| showReloadButton == "true") {
										html += "<button type='button' class='btn btn-default pager-btn' page-btn-fn='refresh' title='刷新' data-toggle='tooltip' data-placement='top'>";
										html += "<span class='icon-refresh' aria-hidden='true'></span></button>";
									}
									html += "</label><label class='pager-right'><span>每页"
											+ pageVo.pageSize
											+ "条，</span><span>共"
											+ pageVo.totalRecord
											+ "条</span></label>";
									$(pages[0]).html(html);
									$('[data-toggle="tooltip"]').tooltip();
								}
							}
						},
						search : function(options) {// 查询数据
							var _datagrid = options.datagrid;
							if (_datagrid != null && _datagrid != undefined) {
								var searchData = null;
								var formId = _datagrid.attr("searchForm");
								if (formId != null && formId != undefined
										&& formId != "") {
									searchData = $("#" + formId).serialize();
								} else {
									var forms = _datagrid.find("form");
									if (forms != null && forms.length > 0) {
										searchData = $(forms[0]).serialize();
									}
								}
								var sortField = _datagrid.attr("sortField");// 排序字段
								var sortOrder = _datagrid.attr("sortOrder");// 排序方式
								var dataField = _datagrid.attr("dataField");// 数据字段名
								var pageSize = _datagrid.attr("pageSize");// 每页多少条
								if (pageSize == null || pageSize == undefined
										|| pageSize <= 0) {
									pageSize = 10;
								}
								var defaultData = {
									sortField : sortField,// 排序字段
									sortOrder : sortOrder,// 排序方式
									pageSize : pageSize,// 每页显示条数
									currentPage : 1
								// 当前页码
								};
								if (options.action != null
										&& options.action != undefined) {
									if (options.action == "update") {// 更新的时候当前页面无需设为1
										defaultData.currentPage = _datagrid
												.parent()
												.find(
														"span[class='currentPage']")
												.html();
									}
								}
								options.data = $.extend(defaultData,
										options.data)
								$.grid.loadData(options, searchData);
							}
						},
						// 数据加载完时执行
						loadSuccess : function(options) {
							var _datagrid = options.datagrid;
							if (_datagrid == null && _datagrid == undefined) {
								return;
							}
							// 注册行点击事件
							var onrowclick = _datagrid.attr("onrowclick");
							if (onrowclick != null && onrowclick != undefined
									&& onrowclick != "") {
								var rowClick = new RowClick(false);
								rowClick.myEvent.addHandler("onrowclick",
										eval(onrowclick))
								_datagrid
										.find("table>tbody>tr")
										.click(
												function() {
													var _row = $(this);
													var checked = _row
															.find("td> label >input:checkbox[name='idField_checkbox']");
													var radio = _row
															.find("td> label >input:radio[name='idField_select']");
													if (checked != null
															&& checked != undefined
															&& checked.length > 0) {
														if (checked[0].checked) {
															rowClick
																	.setChecked(
																			true,
																			checked[0].value);
														} else {
															rowClick
																	.setChecked(
																			false,
																			checked[0].value);
														}
													} else if (radio != null
															&& radio != undefined
															&& radio.length > 0) {
														if (radio[0].checked) {
															rowClick
																	.setChecked(
																			true,
																			radio[0].value);
														} else {
															rowClick
																	.setChecked(
																			false,
																			radio[0].value);
														}
													}
												});
							}
							_datagrid.find(".select_pagesize").change(
									function() {// 选择页面显示条数
										var pages = $(this).closest(
												".page_grid_foot");
										_datagrid.attr("pageSize", $(this)
												.val());// 排序字段
										$.grid.search({
											datagrid : _datagrid
										});
									});
							_datagrid
									.find('.checkAll')
									.change(
											// 全选按钮点击事件
											function() {
												var table = $(this).closest(
														"table");
												var checkedCls = _datagrid
														.attr("checkedCls");
												var rowCls = _datagrid
														.attr("rowCls");
												if (checkedCls == null
														|| checkedCls == undefined) {
													checkedCls = "row_checked";
												}
												if (rowCls == null
														|| rowCls == undefined) {
													rowCls = "row_cls";
												}
												var objs = table
														.find("input:checkbox[name='idField_checkbox']");
												if (this.checked) {
													objs.prop("checked", true);
													_datagrid
															.find(
																	"table>tbody >tr")
															.each(
																	function() {
																		$(this)
																				.attr(
																						"class",
																						checkedCls);
																	});
												} else {
													objs.prop("checked", false);// jquery1.6版本
													_datagrid
															.find(
																	"table>tbody >tr")
															.each(
																	function() {
																		$(this)
																				.attr(
																						"class",
																						rowCls);
																	});
												}
											});
							_datagrid
									.find(".pager-btn")
									.click(
											function() {// 翻页按钮点击事件
												var pages = $(this).closest(
														".page_grid_foot");
												var currentPage = pages
														.find(
																"span[class='currentPage']")
														.html();
												var totalPage = pages
														.find(
																"span[class='totalPage']")
														.html();
												if (currentPage != null) {
													currentPage = parseInt(currentPage);
												}
												if (totalPage != null) {
													totalPage = parseInt(totalPage);
												}
												var data = {};
												var page_btn_fn = $(this).attr(
														"page-btn-fn");
												if (page_btn_fn != null
														&& page_btn_fn != undefined) {
													if (page_btn_fn == "first") {
														if (currentPage == 1) {
															return;
														} else {
															data.currentPage = 1;
														}
													} else if (page_btn_fn == "prev") {
														if (currentPage == 1) {
															return;
														} else if (currentPage > 1) {
															data.currentPage = currentPage - 1;
														}
													} else if (page_btn_fn == "next") {
														if (currentPage == totalPage) {
															return;
														} else if (currentPage < totalPage) {
															data.currentPage = currentPage + 1;
														}
													} else if (page_btn_fn == "last") {
														if (currentPage == totalPage) {
															return;
														} else if (currentPage < totalPage) {
															data.currentPage = totalPage;
														}
													} else if (page_btn_fn == "refresh") {
														data.currentPage = currentPage;
													} else if (page_btn_fn == "go") {
														var num = parseInt($(
																this).prev()
																.val());
														if (!isNaN(num)
																&& num <= totalPage
																&& num > 0
																&& num != currentPage) {
															data.currentPage = num;
														} else {
															$(this).prev().val(
																	"");
															return;
														}
													}
													$.grid.search({
														datagrid : _datagrid,
														data : data
													});
												}
											});
							_datagrid.find("table>thead>tr>th").click(
									function() {
										var _thisth = $(this);
										var allowSort = _thisth
												.attr("allowSort");// 是否允许排序
										var fieldName = _thisth.attr("name");// 列对应字段名
										var sortField = _datagrid
												.attr("sortField");// 排序字段
										var sortOrder = _datagrid
												.attr("sortOrder");// 排序方式
										if (allowSort != null
												&& allowSort != undefined
												&& allowSort == "true") {
											if (fieldName == sortField) {
												if (sortOrder == "desc") {
													_datagrid.attr("sortOrder",
															"asc");
												} else {
													_datagrid.attr("sortOrder",
															"desc");
												}
											} else {
												_datagrid.attr("sortField",
														fieldName);
												_datagrid.attr("sortOrder",
														"desc");
											}
											$.grid.search({
												datagrid : _datagrid,
												action : "update"
											});
										}
									});
							var type = _datagrid.attr("type");
							if (type != null && type != undefined
									&& type == "treegrid") {
								var _table = null;
								var defaults = {
									parentIconClose : "icon-folder-close",// 父节点收拢图标
									parentIconOpen : "icon-folder-open"// 父节点展开图标
								};
								var treeColumn = _datagrid.attr("treeColumn");
								var parentIconClose = _datagrid
										.attr("parentIconClose");
								var parentIconOpen = _datagrid
										.attr("parentIconOpen");
								if (parentIconClose != null
										&& parentIconClose != undefined
										&& parentIconClose != "") {
									defaults.parentIconClose = parentIconClose;
								}
								if (parentIconOpen != null
										&& parentIconOpen != undefined
										&& parentIconOpen != "") {
									defaults.parentIconOpen = parentIconOpen;
								}
								defaults.treeColumn = treeColumn;
								_datagrid.find("table>tbody>tr>td>a").click(
										function(e) {
											e.stopPropagation();// 阻止子元素触发父元素的事件
											_table = $(this).closest("table");
											$.grid.hideOrShowChild($(this)
													.closest("tr"), _table,
													defaults);
										});
							}
							var checkedCls = _datagrid.attr("checkedCls");
							var rowCls = _datagrid.attr("rowCls");
							if (checkedCls == null || checkedCls == undefined) {
								checkedCls = "row_checked";
							}
							if (rowCls == null || rowCls == undefined) {
								rowCls = "row_cls";
							}
							var checkeds = _datagrid
									.find("table>tbody >tr > td> label >input:checkbox[name='idField_checkbox']");
							var radios = _datagrid
									.find("table>tbody >tr > td> label >input:radio[name='idField_select']");
							checkeds
									.change(function() {
										if (this.checked) {
											$(this).closest("tr").attr("class",
													checkedCls);
										} else {
											$(this).closest("tr").attr("class",
													rowCls);
										}
									});
							radios
									.change(function() {
										if (this.checked) {
											$(this).closest("tr").attr("class",
													checkedCls);
										} else {
											$(this).closest("tr").attr("class",
													rowCls);
										}
									});
						},
						hideOrShowChild : function(_thistr, _thistable, opts) {
							var _selfTarget = _thistr.attr("selfTarget");
							var _status = _thistr.attr("status");
							var _childtr = _thistable
									.find("tbody>tr[parentTarget='"
											+ _selfTarget + "']");
							if (_status == "open") {
								_thistr.attr("status", "close");
								// 更换图标
								_thistr.find(
										"td[name='" + opts.treeColumn + "']")
										.find("a>span").attr("class",
												opts.parentIconClose);
								_childtr.hide(300);
								_childtr.each(function(index, e) {
									_status = $(e).attr("status");
									if (_status != null && _status != undefined
											&& _status == "open") {
										$.grid.hideOrShowChild($(e),
												_thistable, opts);
									}
								});
							} else {
								_thistr.attr("status", "open");
								// 更换图标
								_thistr.find(
										"td[name='" + opts.treeColumn + "']")
										.find("a>span").attr("class",
												opts.parentIconOpen);
								_childtr.show(300);
							}
						},
						getSelectedKeys : function(options) {
							var _gridId = null;
							var _datagrid = null;
							var _index = 0;
							if (options != null && options != "") {
								_gridId = options.gridId;
								_datagrid = options.datagrid;
								_index = options.index;
							}
							if (_datagrid == null || _datagrid == undefined) {
								if (_gridId != null && _gridId != undefined) {
									_datagrid = $("#" + _gridId);
								} else {
									var dataGrids = $(".boot-dataGrid");
									if (dataGrids != null
											&& dataGrids != undefined
											&& dataGrids.length > 0) {
										if (_index == null
												|| _index == undefined
												|| _index < 0) {
											_index = 0;// 默认为第一个表格
										} else if (_index >= dataGrids.length) {
											_index = dataGrids.length - 1;
										}
									}
									_datagrid = $(dataGrids[_index]);
								}
							}
							var checkeds = null;
							var radios = null;
							if (_datagrid != null && _datagrid != undefined) {
								checkeds = _datagrid
										.find("table>tbody >tr > td> label >input:checkbox[name='idField_checkbox']:checked");
								radios = _datagrid
										.find("table>tbody >tr > td> label >input:radio[name='idField_select']:checked");
							}
							var ids = [];
							if ((checkeds == null && radios == null)
									|| (checkeds.length == 0 && radios.length == 0)) {
								return ids;
							} else {
								if (checkeds.length > 0) {
									checkeds.each(function(i) {
										ids.push(this.getAttribute("value"));
									});
								} else if (radios.length > 0) {
									radios.each(function(i) {
										ids.push(this.getAttribute("value"));
									});
								}
							}
							return ids;
						},
						ifCheckedOnRowClick : function(options) {
							var _datagrid = null;
							if (options != null && options != "") {
								_datagrid = options.datagrid;
							}
							if (_datagrid != null && _datagrid != undefined) {
								// 行点击是否选中行
								var selectOnRowClick = _datagrid
										.attr("selectOnRowClick");
								if (selectOnRowClick == null
										|| selectOnRowClick == undefined
										|| selectOnRowClick == "true") {
									var checkedCls = _datagrid
											.attr("checkedCls");
									var rowCls = _datagrid.attr("rowCls");
									if (checkedCls == null
											|| checkedCls == undefined) {
										checkedCls = "row_checked";
									}
									if (rowCls == null || rowCls == undefined) {
										rowCls = "row_cls";
									}
									_datagrid
											.find(
													"table>tbody>tr>td> label >input:checkbox[name='idField_checkbox']")
											.click(
													function(e) {
														$(this).prop("checked",
																!this.checked);
													});
									_datagrid
											.find(
													"table>tbody>tr>td> label >input:radio[name='idField_select']")
											.click(
													function(e) {
														$(this).prop("checked",
																!this.checked);
													});
									_datagrid
											.find("table>tbody>tr")
											.click(
													function() {
														var checkboxs = $(this)
																.find(
																		"td> label >input:checkbox[name='idField_checkbox']");
														var radios = $(this)
																.find(
																		"td> label >input:radio[name='idField_select']");
														if (checkboxs != null
																&& checkboxs.length > 0) {
															checkboxs
																	.each(function() {
																		$(this)
																				.prop(
																						"checked",
																						!this.checked);
																		if (this.checked) {
																			$(
																					this)
																					.closest(
																							"tr")
																					.attr(
																							"class",
																							checkedCls);
																		} else {
																			$(
																					this)
																					.closest(
																							"tr")
																					.attr(
																							"class",
																							rowCls);
																		}
																	});
														} else if (radios != null
																&& radios.length > 0) {
															_datagrid
																	.find(
																			"table>tbody >tr")
																	.each(
																			function() {
																				$(
																						this)
																						.attr(
																								"class",
																								rowCls);
																			});
															radios
																	.each(function() {
																		$(this)
																				.prop(
																						"checked",
																						!this.checked);
																		if (this.checked) {
																			$(
																					this)
																					.closest(
																							"tr")
																					.attr(
																							"class",
																							checkedCls);
																		} else {
																			$(
																					this)
																					.closest(
																							"tr")
																					.attr(
																							"class",
																							rowCls);
																		}
																	});
														}
													});
								}
							}
						},
						deleteDate : function(options) {// 删除数据
							var defaults = {
								url : "",
								allowbatch : true,// 允许批量删除
								paramName : "keys"
							};
							var opts = $.extend(defaults, options);
							var ids = $.grid.getSelectedKeys(opts);
							if (ids == null || ids.length == 0) {
								$btools.alert("请选择要删除的数据！");
								return;
							}
							if (!opts.allowbatch) {
								if (ids.length > 1) {
									$btools.alert("不允许批量删除！");
									return;
								}
							}
							$btools
									.prompt(
											"您确定删除选中数据？",
											function() {
												$btools.blockUI({
													msg : "正在删除数据，请稍候..."
												});
												$
														.ajax({
															cache : true,
															// async: false,
															type : "POST",
															url : opts.url,
															data : opts.paramName
																	+ "="
																	+ ids
																			.join(","),
															error : function(
																	request) {
																$btools
																		.alert(
																				"请求出错~",
																				function() {
																					$btools
																							.unblockUI();// 隐藏加载提示框
																				});
																return;
															},
															success : function(
																	data) {
																$btools
																		.unblockUI();// 隐藏加载提示框
																opts.data = data;
																opts.refrsh = true;
																$btools
																		.dataHandle(opts);
															}
														});
											});
						}
					});
	$.grid = new DataGrid();
	$(document)
			.ready(
					function() {
						// 页面加载完成时执行的函数
						$btools.loadinghide();// 隐藏加载提示框
						$btools.unblockUI();// 关闭遮罩层
						var dataGrids = $(".boot-dataGrid");
						dataGrids.each(function(index) {
							// 设置.boot-dataGrid的可用高度
							var _this = $(this);
							// 表格初始化
							if (_this.attr("init") != undefined) {
								$.grid.init({
									datagrid : _this
								});
							} else {
								$.grid.loadPager({
									datagrid : _this
								}, null);
								$.grid.loadSuccess({
									datagrid : _this
								});
							}
							_this.find(".page_grid_body").css(
									"height",
									(_this.height()
											- _this.find(".page_grid_head")
													.height()
											- _this.find(".page_grid_foot")
													.height() - 10)
											+ "px");
						});
						$(".fn-btn")
								.click(
										function(e) {
											e.preventDefault();
											var _this = $(this);
											var fun = _this.attr("btn-fn");
											var _datagridId = _this
													.attr("datagrid");
											var _datagrid = $(_this
													.closest(".boot-dataGrid")[0]);
											if (_datagridId != null
													&& _datagridId != undefined
													&& _datagridId != "") {
												_datagrid = $("#" + _datagridId);
											}
											var _options = _this
													.attr("options");
											var options = {};
											try {
												if (_options != null
														&& _options != undefined) {
													options = eval('('
															+ _options + ')');
												}
											} catch (e) {
											}
											if (fun != null && fun != undefined) {
												if (fun == "search") {// 点击查询按钮
													if (_datagrid != null
															&& _datagrid != undefined) {
														$.grid
																.search({
																	datagrid : _datagrid
																});
													}
												} else if (fun == "add") {// 打开添加模态框
													var defaults = {
														ondestroyed : function(
																opts) {// 模态框销毁之后,刷新表格
															$.grid
																	.search({
																		datagrid : _datagrid
																	});
														}
													};
													var opts = $.extend(
															defaults, options);
													$btools
															.openUrlInModal(opts);
												} else if (fun == "edit") {// 打开模态框
													var ids = $.grid
															.getSelectedKeys({
																datagrid : _datagrid
															});// 获取主键
													if (ids.length > 1) {
														$btools
																.alert("只能修改一条数据！");
														return;
													} else if (ids.length <= 0) {
														$btools
																.alert("请选择要修改的数据！");
														return;
													} else if (ids == null) {
														$btools.alert("操作失败！");
														return;
													}
													var defaults = {
														action : "update",
														formId : "dataForm",
														paramName : "key",
														onload : function(opts) {// 模态框创建完成
															if (opts.iframe != null
																	&& opts.iframe.contentWindow.$.form != null) {
																opts.iframe.contentWindow.$.form
																		.showedit({
																			primarykey : ids[0],
																			dataUrl : opts.dataUrl,
																			formId : opts.formId,
																			paramName : opts.paramName
																		});
															}
														},
														ondestroyed : function(
																opts) {// 模态框销毁之后,刷新表格
															$.grid
																	.search({
																		datagrid : _datagrid,
																		action : opts.action
																	});
														}
													}
													var opt = $.extend(
															defaults, options);
													$btools.openUrlInModal(opt);
												} else if (fun == "delete") {
													var defaults = {
														allowbatch : true,
														datagrid : _datagrid
													}
													var opts = $.extend(
															defaults, options);
													$.grid.deleteDate(opts);
												}
											}
										});
						if ($('[tableConfig]').length > 0) {
							var defaults = {
								width : "50%",
								iconCls : "icon-cog",
								headerCls : "modal-header",
								title : "表格配置",
								url : "",
								backdrop : true,
								keyboard : true
							}
							$('[tableConfig]')
									.click(
											function() {
												var _this = $(this);
												var _options = _this
														.attr("options");
												var options = {};
												try {
													if (_options != null
															&& _options != undefined) {
														options = eval('('
																+ _options
																+ ')');
													}
												} catch (e) {
												}
												var opts = $.extend(defaults,
														options);
												if (opts.url != undefined
														&& opts.url != ""
														&& opts.defaultDataUrl != undefined
														&& opts.defaultDataUrl != "") {
													opts.url = opts.url
															+ "?url="
															+ opts.defaultDataUrl;
												}
												$btools.openUrlInModal(opts);
											});
						}
					});
	Date.prototype.format = function(fmt) { // author: meizz
		var o = {
			"M+" : this.getMonth() + 1, // 月份
			"d+" : this.getDate(), // 日
			"h+" : this.getHours(), // 小时
			"m+" : this.getMinutes(), // 分
			"s+" : this.getSeconds(), // 秒
			"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
			"S" : this.getMilliseconds()
		// 毫秒
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
					.substr(4 - RegExp.$1.length));
		for ( var k in o)
			if (new RegExp("(" + k + ")").test(fmt))
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
						: (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	}

	// 自定义事件注册
	function MyEvent() {
		this.handlers = {};
	}
	MyEvent.prototype = {
		addHandler : function(type, handler) {
			if (typeof this.handlers[type] == "undefined") {
				this.handlers[type] = [];
			}
			this.handlers[type].push(handler);
		},
		fire : function(event) {
			if (this.handlers[event.type] instanceof Array) {
				var handlers = this.handlers[event.type];
				for (var i = 0, len = handlers.length; i < len; i++) {
					handlers[i](event);
				}
			}
		},
		removeHandler : function(type, handler) {
			if (this.handlers[type] instanceof Array) {
				var handlers = this.handlers[type];
				for (var i = 0, len = handlers.length; i < len; i++) {
					if (handlers[i] === handler) {
						break;
					}
				}
				handlers.splice(i, 1);
			}
		}
	};
	function RowClick(checked) {// 表格行点击事件
		this.myEvent = new MyEvent();
		this.checked = checked;// 行选中状态
		this.value = "";// 该行主键值
	}
	RowClick.prototype = {
		setChecked : function(checked, value) {
			var eventStart = {
				type : "onrowclick",
				checked : checked,
				value : value
			};
			this.myEvent.fire(eventStart);
			this.checked = checked;
			this.value = value;
		}
	}
})(jQuery);